package com.qk.aop;

import com.qk.common.Result;
import com.qk.entity.OperateLog;
import com.qk.mapper.OperateLogMapper;
import com.qk.utils.CurrentUserHoler;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

/**
 * @author 28188
 */
@Aspect
@Component
public class LogAspect {

    @Autowired
    private OperateLogMapper operateLogMapper;

    @Pointcut("@annotation(com.qk.aop.anno.LogOperation)")
    public void logPointCut() {
    }

    @Around("logPointCut()")
    public Object aroundAdvice(ProceedingJoinPoint joinPoint) {
        Object result;
        try {
            // 开始时间
            long startTime = System.currentTimeMillis();
            // 参数
            Object[] args = joinPoint.getArgs();
            String methodParams = Arrays.toString(args);
            // 返回值
            result = joinPoint.proceed();
            // 耗时
            long costTime = System.currentTimeMillis() - startTime;
            // 操作日志
            OperateLog operateLog = new OperateLog();
            operateLog.setOperateUserId(CurrentUserHoler.getCurrentUser());
            operateLog.setOperateTime(LocalDateTime.now());
            operateLog.setClassName(joinPoint.getTarget().getClass().getName());
            operateLog.setMethodName(joinPoint.getSignature().getName());
            operateLog.setMethodParams(methodParams);
            operateLog.setReturnValue(result.toString());
            operateLog.setCostTime(costTime);
            operateLogMapper.insert(operateLog);
        } catch (Throwable e) {
            result = Result.error("操作失败");
        }
        return result;
    }
}
